/*
 * escritor.cpp
 *
 *  Created on: Oct 30, 2013
 *      Author: m
 */

#include <iostream>
#include <cstdlib>
#include <ctime>
#include "DefinicionesComunes.h"
#include "NewMessageQueue.h"
#include "NewSemaphore.h"
#include "NewSharedMemory.h"
#include "Sequence.h"
#include "CPrinter.h"

#define MAX_VARIACIONDOLAR 0.5

using namespace ipc;

int main ( int argc, char* argv[] )
{
    int nLectoresConsecutivos;
    float variacionDolar;
    float valorDolar;
    int id;

    srand( time( NULL ) );

    id = Sequence::get( IPC_BASE_FILE, SEQ_ID_ESCRIT ).getNext();

    CPrinter::setHeader( "escritor", id );

    // IPCs
    SharedMemory<float> shmPrecioDolar =
            SharedMemory<float>::get( IPC_BASE_FILE, SHM_BOARD );
    Semaphore semEscritor =
            Semaphore::get( IPC_BASE_FILE, SEM_ESCRITOR );

    CPrinter::printOut( "INICIADO" );

    Semaphore::get( IPC_BASE_FILE, SEM_INICIO ).p();

    while ( true )
    {
        sleep( random() % 10 );

        semEscritor.p();

        valorDolar = shmPrecioDolar.read();

        variacionDolar = ( ( (float)random() ) / RAND_MAX ) * MAX_VARIACIONDOLAR;

        if ( variacionDolar == 0 )
        {
            variacionDolar = 0.01;
        }

        if ( random() % 2 == 1 )
        {
            valorDolar += variacionDolar;
        }
        else
        {
            valorDolar -= variacionDolar;

            if ( valorDolar < 0 )
            {
                valorDolar = 0;
            }
        }

        sleep( random() % 10 );

        CPrinter::printOut( "Nuevo valor del dolar: $%.2f", valorDolar );

        shmPrecioDolar.write( valorDolar );

        semEscritor.v();
    }

    return 0;
}
